package com.cskaoyan.market.admin.controller;

import com.cskaoyan.market.admin.service.MarketUserService;
import com.cskaoyan.market.db.domain.MarketUser;
import com.cskaoyan.market.util.JacksonUtil;
import com.cskaoyan.market.util.ResponseUtil;
import com.cskaoyan.market.util.ZhouWenUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;


/**
 * @author yuanixn2158@163.com
 * @since 2023/05/09 11:27
 */


@RestController
@RequestMapping("/admin/user")
public class AdminUserController{
    @Autowired
    MarketUserService marketUserService;
    
    @GetMapping("/detail")
    private void detail(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String idStr = req.getParameter("id");
        if (StringUtils.isEmpty(idStr)) {
            resp.getWriter().println(ResponseUtil.badArgumentValue());
            return;
        }
        Integer id = null;
        try {
            id = Integer.parseInt(idStr);
        } catch (Exception e) {
            resp.getWriter().println(ResponseUtil.badArgumentValue());
            return;
        }
        MarketUser marketUser = marketUserService.getUserDetail(id);
        Object ok = ResponseUtil.ok(marketUser);
        resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ok));

    }

    @GetMapping("/list")
    private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        int page = Integer.parseInt(req.getParameter("page"));
        int limit = Integer.parseInt(req.getParameter("limit"));
        String sort = req.getParameter("sort");
        String order = req.getParameter("order");
        List<MarketUser> marketUserList = marketUserService.getUserList(page, limit, sort, order);
        Object ok = ResponseUtil.okList(marketUserList);
        resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ok));


    }
    

    @PostMapping("/update")
    private void update(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String requestBody = ZhouWenUtil.getRequestBody(req);
        MarketUser updateMarketUser = JacksonUtil.getObjectMapper().readValue(requestBody, MarketUser.class);
        MarketUser marketUser=marketUserService.Update(updateMarketUser);
        Object ok = ResponseUtil.ok(1);
        resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ok));
    }
}
